package com.movitech.mobile.cz.base.supplier.bizservice.impl;

import com.movitech.mobile.cz.base.bizconfig.service.impl.MessageUtilService;
import com.movitech.mobile.cz.base.common.license.LicenseUtil;
import com.movitech.mobile.cz.base.common.util.CommonConstants;
import com.movitech.mobile.cz.base.common.util.PageCode;
import com.movitech.mobile.cz.base.common.util.StringUtils;
import com.movitech.mobile.cz.base.common.utils.IdGen;
import com.movitech.mobile.cz.base.modules.config.*;
import com.movitech.mobile.cz.base.supplier.bizservice.SSuppliersIntranetService;
import com.movitech.mobile.cz.base.supplier.bizvo.SuppliersIntranetRequestVO;
import com.movitech.mobile.cz.base.supplier.entity.*;
import com.movitech.mobile.cz.base.supplier.entity.ext.ExtSysUserResponseVO;
import com.movitech.mobile.cz.base.supplier.entity.ext.SuppliersListRequestVO;
import com.movitech.mobile.cz.base.supplier.entity.ext.SuppliersUpdatePasswordRequestVO;
import com.movitech.mobile.cz.base.supplier.entity.ext.SuppliersUpdateStaticRequestVO;
import com.movitech.mobile.cz.base.supplier.mapper.SSupplierContactInfoMapper;
import com.movitech.mobile.cz.base.supplier.mapper.SSuppliersMapper;
import com.movitech.mobile.cz.base.supplier.mapper.ext.ExtSSuppliersMapper;
import com.movitech.mobile.cz.base.supplier.service.*;
import com.movitech.mobile.cz.base.sys.bizvo.AttachmentVO;
import com.movitech.mobile.cz.base.sys.entity.SAttachment;
import com.movitech.mobile.cz.base.sys.entity.SysUser;
import com.movitech.mobile.cz.base.sys.mapper.SysUserMapper;
import com.movitech.mobile.cz.base.sys.service.SAttachmentService;
import com.movitech.mobile.cz.base.sys.service.SRegionalCompanyService;
import com.movitech.mobile.cz.base.sys.service.SysUserService;
import com.movitech.mobile.cz.base.util.UserUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by Blue.Xia on 2018/3/5.
 */
@Service
@Transactional
public class SSuppliersIntranetServiceImpl implements SSuppliersIntranetService {

    @Autowired
    private SSuppliersMapper sSuppliersMapper;

    @Autowired
    private ExtSSuppliersMapper extSSuppliersMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SSupplierContactInfoMapper sSupplierContactInfoMapper;

    @Autowired
    private SHistoryCommentService sHistoryCommentService;

    @Autowired
    private SCommentConfigService sCommentConfigService;

    @Autowired
    private SAttachmentService sAttachmentService;

    @Autowired
    private SSupplierRcRelateService sSupplierRcRelateService;

    @Autowired
    private SSupplierCategoryRelateService sSupplierCategoryRelateService;

    @Autowired
    private MessageUtilService messageUtilService;
    @Autowired
    private SRegionalCompanyService sRegionalCompanyService;
    @Autowired
    private SMyDealsService sMyDealsService;



    /**
     * 内网供方新增
     *
     * @param suppliersIntranetRequestVO
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = { "RuntimeException", "Exception" })
    public boolean insertSupplierIntranet(SuppliersIntranetRequestVO suppliersIntranetRequestVO) {
        SysUser sysUser = new SysUser();
        String password=sysUserService.createPassword();
        String userId = IdGen.uuid();
        sysUser.setId(userId);
        sysUser.setPassword(DigestUtils.md5Hex(password));
        sysUser.setLoginName(suppliersIntranetRequestVO.getLoginName());
        sysUser.setName(suppliersIntranetRequestVO.getLoginName());
        sysUser.setMobile(suppliersIntranetRequestVO.getLoginName());
        sysUser.setRemarks(password);
        sysUser.setLoginFlag(CommonConstants.YES_LOGIN);
        sysUser.setUserType(CommonConstants.EXTERNAL_USER);
        sysUser.setBaseFeilds(UserUtils.getCurrentUserId(),null,0,true);
        int userResult = sysUserMapper.insert(sysUser);
        if (userResult <= 0) {
            throw new RuntimeException("系统错误");
        }

        LicenseUtil.INSTANCE.validate();
//        String smsValue=sCommentConfigService.getValueByCode(CommentConfigEnum.REFISTER_SMS.getCode());
//        smsValue=smsValue.replace("[0]",sysUser.getLoginName());
//        smsValue=smsValue.replace("[1]",sysUser.getPassword());
//        if(!smsUtil.sendSms(sysUser.getLoginName(),smsValue)){
//            throw new RuntimeException("系统错误");
//        }
        String configValue=sCommentConfigService.getValueByCode(CommentConfigEnum.REFISTER_SMS.getCode());
        messageUtilService.messageSendAsyn(configValue,sysUser.getLoginName(),new String[]{sysUser.getLoginName(),password});

        SSuppliers sSuppliers = new SSuppliers();
        String supplierId = IdGen.uuid();
        sSuppliers.setId(supplierId);
        sSuppliers.setSysUserId(userId);
        sSuppliers.setCompanyName(suppliersIntranetRequestVO.getCompanyName());
        sSuppliers.setSupplierServiceCategoryIds(suppliersIntranetRequestVO.getSupplierServiceCategoryIds());
        sSuppliers.setSupplierCategoryIds(suppliersIntranetRequestVO.getSupplierCategoryIds());
        sSuppliers.setApplyUserId(suppliersIntranetRequestVO.getApplyUserId());
        sSuppliers.setRegisterStatus(Integer.parseInt(RegisterStatusEnum.STORE_APPROVE_ING.getCode()));
        sSuppliers.setSupplierStatus(Integer.parseInt(SupplierStatusEnum.QUALIFICATION_INSPECTION.getCode()));
        sSuppliers.setSupplierBigStatus(SupplierBigStatusEnum.POTENTIAL.getCode());
        sSuppliers.setIntentionRegionalCompanyIds(suppliersIntranetRequestVO.getIntentionRegionalCompanyIds());
        sSuppliers.setUndertakeAreas(suppliersIntranetRequestVO.getUndertakeAreas());
        sSuppliers.setBaseFeilds(UserUtils.getCurrentUserId(),null,0,true);
        sSuppliers.setRegisterTime(new Date());
        //企业编码  时间戳13位 入库时同步主数据后，从主数据返回
//        sSuppliers.setCompanyCode(System.currentTimeMillis()+"");
        int supplierResult = sSuppliersMapper.insert(sSuppliers);
        if (supplierResult <= 0) {
            throw new RuntimeException("系统错误");
        }

        //意向公司关系表保存
        String intentionRegionalCompanyIds=suppliersIntranetRequestVO.getIntentionRegionalCompanyIds();
        if(StringUtils.isNotEmpty(intentionRegionalCompanyIds)){
            String[] intentionRegionalCompanyIdArr=intentionRegionalCompanyIds.split(",");
            List<SSupplierRcRelate> sSupplierRcRelatels=new ArrayList();
            for(String intentionRegionalCompanyId:intentionRegionalCompanyIdArr){
                SSupplierRcRelate obj=new SSupplierRcRelate();
                obj.setId(IdGen.uuid());
                obj.setSuppliersId(sSuppliers.getId());
                obj.setRegionalCompanyId(intentionRegionalCompanyId);
                obj.setSupplierCategoryIds(sSuppliers.getSupplierCategoryIds());
                obj.setSupplierServiceCategoryIds(sSuppliers.getSupplierServiceCategoryIds());
                obj.setSupplierStatus(Integer.parseInt(SupplierStatusEnum.QUALIFICATION_INSPECTION.getCode()));
                obj.setSupplierBigStatus(SupplierBigStatusEnum.POTENTIAL.getCode());
                obj.setBaseFeilds(UserUtils.getCurrentUserId(),null,0,true);
                obj.setSupplierSource(SupplierSourceEnum.ADD.getCode());
                sSupplierRcRelatels.add(obj);

                //内网新增供方给意向地区公司发送资质审查待办
//                SRegionalCompany sRegionalCompany = sRegionalCompanyService.selectById(intentionRegionalCompanyId);
//                if(sRegionalCompany!=null&&StringUtils.isNotEmpty(sRegionalCompany.getSupplierMngUsers())){
//                    String[] mngUserIdArr=sRegionalCompany.getSupplierMngUsers().split(",");
//                    if(mngUserIdArr!=null&&mngUserIdArr.length>0){
//                        for(String mngUserId:mngUserIdArr){
//                            SMyDeals sMyDeals = new SMyDeals();
//                            sMyDeals.setUserId(mngUserId);
//                            sMyDeals.setDealEndTime(new Date());
//                            String titleTemplate = sCommentConfigService.getValueByCode(CommentConfigEnum.MY_DEAL_TEMPLATE.getCode());
//                            String title = MessageFormat.format(titleTemplate, MyDealSubTypeEnum.QUALIFICATION_INSPECTION.getDesc(), sSuppliers.getCompanyName()+MyDealSubTypeEnum.QUALIFICATION_INSPECTION.getDesc());
//                            sMyDeals.setDealTitle(title);
//                            sMyDeals.setDealType(DealTypeEnum.SUPPLIERS.getCode());//类型（1：供方，2：采购）
//                            sMyDeals.setRelatedId(sSuppliers.getId());
//                            sMyDeals.setSubRelatedId(obj.getId());
//                            sMyDeals.setActionType(MyDealActionTypeEnum.QUALIFICATION_INSPECTION.getCode());
//                            sMyDeals.setDealSubType(MyDealSubTypeEnum.QUALIFICATION_INSPECTION.getCode());
//                            sMyDeals.setBaseFeilds(UserUtils.getCurrentUserId(), null, 0, true);
//                            sMyDealsService.saveSMyDeals(sMyDeals);
//                        }
//                    }
//                }
            }
            sSupplierRcRelateService.insertBatch(sSupplierRcRelatels);
        }

        //供方基本情况-供方分类关系表保存
        String supplierCategoryIds=suppliersIntranetRequestVO.getSupplierCategoryIds();
        if(StringUtils.isNotEmpty(supplierCategoryIds)){
            String[] supplierCategoryIdArr=supplierCategoryIds.split(",");
            List<SSupplierCategoryRelate> sSupplierCategoryRelateLs=new ArrayList<>();
            for(String supplierCategoryId:supplierCategoryIdArr){
                SSupplierCategoryRelate obj=new SSupplierCategoryRelate();
                obj.setId(IdGen.uuid());
                obj.setSuppliersId(sSuppliers.getId());
                obj.setCategoryId(supplierCategoryId);
                obj.setBaseFeilds(UserUtils.getCurrentUserId(),null,0,true);
                sSupplierCategoryRelateLs.add(obj);
            }
            sSupplierCategoryRelateService.insertBatch(sSupplierCategoryRelateLs);
        }

        SSupplierContactInfo sSupplierContactInfo = new SSupplierContactInfo();
        sSupplierContactInfo.setId(IdGen.uuid());
        sSupplierContactInfo.setSuppliersId(supplierId);
        sSupplierContactInfo.setContactName(suppliersIntranetRequestVO.getContactName());
        sSupplierContactInfo.setMobile(suppliersIntranetRequestVO.getContactPhone());
        sSupplierContactInfo.setMainFlag(CommonConstants.COMMON_CONTACTS);//是否主联系人（0：否，1：是）
        sSupplierContactInfo.setBaseFeilds(UserUtils.getCurrentUserId(),null,0,true);
        int supplierContact = sSupplierContactInfoMapper.insert(sSupplierContactInfo);
        if (supplierContact <= 0) {
            throw new RuntimeException("系统错误");
        }
        //保存供方入库申请附件
        List<AttachmentVO> ls=suppliersIntranetRequestVO.getAttachmentVOLs();
        for(AttachmentVO attachmentVO:ls) {
            SAttachment sAttachment=new SAttachment();
            BeanUtils.copyProperties(attachmentVO,sAttachment);
            sAttachment.setAttachmentType(12);//14：供方入库申请附件 12：供方其他附件
            sAttachment.setFormId(supplierId);
            sAttachment.setRelatedId(supplierId);
            sAttachment.setId(IdGen.uuid());
            sAttachment.setBaseFeilds(UserUtils.getCurrentUserId(),null,0,true);
            sAttachmentService.insert(sAttachment);
        }

        //保存日志
        boolean historyCommentFlag = saveSHistoryComment(supplierId);
        if(!historyCommentFlag){
            throw new RuntimeException("系统错误");
        }

        return true;
    }

    private boolean saveSHistoryComment(String relatedId) {
        LicenseUtil.INSTANCE.validate();
        SHistoryComment sHistoryComment = new SHistoryComment();
        sHistoryComment.setModelType(HistoryCommentModelTypeEnum.AUDIT_PROCESS_SUPPLIERS_INFO.getCode());
        sHistoryComment.setRelatedId(relatedId);
        sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.SUPPLIER_INTRANET_ADD_HISTORY_COMMENT_NODE_NAME.getCode()));
        sHistoryComment.setCommentContent(null);
        sHistoryComment.setActionName(sCommentConfigService.getValueByCode(CommentConfigEnum.SUPPLIER_INTRANET_ADD_HISTORY_COMMENT_ACTION_NAME.getCode()));
        sHistoryComment.setCommentType(HistoryCommentTypeEnum.INTRANET_INTERNET.getCode());
        sHistoryComment.setSetupTime(new Date());
        boolean historyCommentFlag = sHistoryCommentService.saveSHistoryComment(sHistoryComment);
        return historyCommentFlag;
    }

    /**
     * 内网供方列表
     * @param suppliersListRequestVO
     * @return
     */
    @Override
    public PageCode findSuppliersList(SuppliersListRequestVO suppliersListRequestVO) {
        PageCode pageCode = new PageCode(suppliersListRequestVO.getPageNumber(), suppliersListRequestVO.getPageSize());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("currentRecordNum", (pageCode.getPageNo() - 1) * pageCode.getPageSize());
        map.put("pageSize", pageCode.getPageSize());
        map.put("loginName", suppliersListRequestVO.getLoginName());
        map.put("companyName", suppliersListRequestVO.getCompanyName());
        map.put("loginFlag", suppliersListRequestVO.getLoginFlag());
        Integer count = extSSuppliersMapper.findSuppliersListCount(map);
        pageCode.setCount(count == null ? 0 : count);
        List<ExtSysUserResponseVO> ls = extSSuppliersMapper.findSuppliersList(map);
        pageCode.setList(ls);
        return pageCode;
    }

    /**
     * 内网供方更细状态
     * @param suppliersUpdateStaticRequestVO
     * @return
     */
    @Override
    public boolean updateSuppliersStatic(SuppliersUpdateStaticRequestVO suppliersUpdateStaticRequestVO) {
        int i = extSSuppliersMapper.updateSuppliersStatic(suppliersUpdateStaticRequestVO);
        return i > 0;
    }

    /**
     * 内网供方更新密码
     * @param suppliersListRequestVO
     * @return
     */
    @Override
    public boolean updateSuppliersPassword(SuppliersUpdatePasswordRequestVO suppliersListRequestVO) {
        int i = extSSuppliersMapper.updateSuppliersPassword(suppliersListRequestVO);
        return i > 0;
    }

}
